import { _decorator, Component, Node, Label, director, game, v3, view } from 'cc';
import { GameEventType, GameOverType } from './Event/EnumDefine';
import { EventManager } from './Event/EventManager';
import { DataConfig } from './Config/DataConfig';
import Common from './Config/Common';
const { ccclass, property } = _decorator;

/** 游戏时间进度倒计时 */
@ccclass('GameTimer')
export class GameTimer extends Component {

    @property(Label)
    timerLabel: Label = null; // 用于显示剩余时间的Label

    private timeRemaining: number = 180; // 3分钟，单位：秒
    private timerActive: boolean = true;

   onLoad(): void {
        EventManager.instance.registerEvent(GameEventType.Game_Start, this.onGameStart, this);

        this.onScreen();
        EventManager.instance.registerEvent(GameEventType.Screen_Change, this.onScreen, this);
    }

    onScreen() {
        this.timerLabel.node.setPosition(v3(0, Common.instance.getEnergyY()));
    }

    onGameStart() {
        // 开始计时
        this.schedule(this.updateTimer, 1);
    }

    updateTimer() {
        if(DataConfig.isGameStop){
            return;
        }
        if (!this.timerActive) return;

        this.timeRemaining -= 1;

        // 更新UI显示
        if (this.timerLabel) {
            const minutes = Math.floor(this.timeRemaining / 60);
            const seconds = this.timeRemaining % 60;
            this.timerLabel.string = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
        }

        // 时间倒数第8秒将不在创建数字块
        if (this.timeRemaining == 8) {
            EventManager.instance.triggerEvent(GameEventType.Stop_Create_Block, null);
        }

        // 时间到，结束游戏
        if (this.timeRemaining <= 0) {
            this.timerActive = false;
            this.gameOver();
        }
    }

    gameOver() {
        EventManager.instance.triggerEvent(GameEventType.Game_Over, GameOverType.TimeOver);
    }
}
